package com.edu.cdp.service.impl;

import com.edu.cdp.DTO.AddStaffDTO;
import com.edu.cdp.DTO.PageDTO;
import com.edu.cdp.DTO.StaffDTO;
import com.edu.cdp.utils.NumberUtils;
import com.edu.cdp.common.PageResult;
import com.edu.cdp.service.CommonService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.cdp.domain.Staff;
import com.edu.cdp.service.StaffService;
import com.edu.cdp.mapper.StaffMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


/**
* @author Yang Can
* @description 针对表【staff】的数据库操作Service实现
* @createDate 2024-05-30 20:48:14
*/
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff>
    implements StaffService{
    @Autowired
    StaffMapper staffMapper;
    @Autowired
    private CommonService commonService;

    @Override
    public Staff newUpdate(StaffDTO staff) {
        Staff oldStaff = staffMapper.selectById(staff.getId());

        if (oldStaff != null) {
            if (staff.getPassword() != null || !staff.getPassword().isEmpty()) {
                oldStaff.setPassword(DigestUtils.md5DigestAsHex(staff.getPassword().getBytes()));
            }

            if (staff.getSex() != null && !staff.getSex().isEmpty()) {
                oldStaff.setSex(staff.getSex());
            }

            if (staff.getName() != null && !staff.getName().isEmpty()) {
                oldStaff.setName(staff.getName());
            }

            if (staff.getPhone() != null && !staff.getPhone().isEmpty()) {
                oldStaff.setPhone(staff.getPhone());
            }

            if (staff.getJobNumber() != null && !staff.getJobNumber().isEmpty()) {
                QueryWrapper<Staff> query = new QueryWrapper<Staff>();
                query.eq("job_number", staff.getJobNumber());

                Staff jobStaff = staffMapper.selectOne(query);

                if (jobStaff == null){
                    oldStaff.setJobNumber(staff.getJobNumber());
                } else {
                    log.error("员工工号已存在");
                    return null;
                }

            }

            return oldStaff;
        } else {
            return null;
        }
    }

    @Override
    public Staff newAdd(AddStaffDTO staffDTO) {
        Staff staff = new Staff();
        NumberUtils jobNumber = new NumberUtils();
        BeanUtils.copyProperties(staffDTO, staff);
        //设置员工默认密码
        staff.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        staff.setJobNumber(jobNumber.getJobNumber());

        int result = staffMapper.insert(staff);

        if (result > 0){
            return staff;
        } else {
            log.error("员工添加失败");
            return null;
        }
    }

    @Override
    public List<Staff> staffByName(String name) {
        QueryWrapper<Staff> query = new QueryWrapper<Staff>();
        query.like("name", name);

        return staffMapper.selectList(query);
    }

    @Override
    public List<Staff> getBySex(String sex) {
        QueryWrapper<Staff> query = new QueryWrapper<Staff>();
        query.eq("sex", sex);

        return staffMapper.selectList(query);
    }

    @Override
    public Staff login(String jobNumber, String password) {
        QueryWrapper<Staff> query = new QueryWrapper<Staff>();

        query.eq("job_number", jobNumber);
        query.eq("password", password);

        return staffMapper.selectOne(query);
    }

    @Override
    public PageResult pageQuery(PageDTO pageDTO) {
        Page<Staff> page = new Page<Staff>(pageDTO.getPageNum(), pageDTO.getPageSize());
        IPage<Staff> staffIPage = staffMapper.selectPage(page, null);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(staffIPage.getTotal());
        pageResult.setList(staffIPage.getRecords());

        return pageResult;
    }

    @Override
    @Transactional // 确保操作的原子性，如果文件上传成功而数据库更新失败，可以回滚
    public Staff updateAvatar(Integer id, MultipartFile avatar) {
        String avatarPath = commonService.upload(avatar);

        if (avatarPath == null || avatarPath.isEmpty()) {
           log.error("头像上传失败");
        }

        Staff staffToUpdate = new Staff();
        staffToUpdate.setId(id);
        staffToUpdate.setAvatar(avatarPath);

        int rowsAffected = staffMapper.update(staffToUpdate,
                Wrappers.<Staff>lambdaUpdate().eq(Staff::getId, id));

        if (rowsAffected > 0) {
            return staffMapper.selectById(id);
        } else {
            return null;
        }
    }
}




